import Vue from "vue";
import Vuex from "vuex";
import {getMenuList} from "@/api"

//引入allRoutes
import allRoutes from "../router/allRoutes"
//引入递归函数
import recursionRoutes from "../untils/recursionRoutes"
//引入动态路由dynamicRoutes
import dynamicRoutes from "../router/dynamicRoutes"

//引入router
import router from "../router"

Vue.use(Vuex);
//刷新视图数据会丢失所以从localStorage获取本地缓存
let userInfo = localStorage.getItem('stu-userInfo') || "{}"
userInfo=JSON.parse(userInfo)


export default new Vuex.Store({
  state: {
    userInfo,
    menuList:[],//定义用户侧边栏菜单
    crubms:[]
  },
  mutations: {
    //更改userInfo
    SET_USERINFO(state,payload){
      state.userInfo=payload;
    },
    SET_MENULIST(state,payload){
      state.menuList = payload;
      // console.log(state.menuList);
      //动态的将路由添加到routes中 核心方法: router.addRoutes(符合路由配置规则的数据)
      //1.将listmenu的值赋值给dynamicRoutes的主页children
      let target = dynamicRoutes.find(item => item.path ==="/")
      target.children = [...state.menuList]
      console.log(dynamicRoutes);
      // 2.动态添加路由配置到router/routers中
      router.addRoutes(dynamicRoutes)
    },
    //设置面包屑
    SET_CRUBMS(state,payload){
      state.crubms = payload;
    }
  },
  actions: {
    //1.发送请求,获取用户菜单
    async FETCH_MENULIST({ commit }){
      // 2.通过allroutes和请求回来的用户菜单数据进行对比
      let userMenu = await getMenuList()
      // console.log(userMenu);
      let sideMenu = recursionRoutes(allRoutes,userMenu.data.menuList)
      //3.将结果提交给SET_MENULIST
      // console.log(sidMenu);
      commit("SET_MENULIST",sideMenu)
    }
  },
  modules: {}
});
